package com.onlinemart.controller;

import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@SuppressWarnings("serial")
public class OnlineServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doProcess(request, response);
    }
    protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
    	
    	HttpSession session= request.getSession();
    	String userName= request.getParameter("emailId");
    	System.out.println("UserName "+userName);
    	String passwd = request.getParameter("password");
    	System.out.println("Password "+passwd);
    	if(userName!=null || passwd!=null)
    	{
    		
    		String requestedURL=request.getRequestURI();
    		String actionUrl=requestedURL.replaceAll(request.getContextPath()+"/", "").trim();
    		String actionType=actionUrl.replaceAll(".do", "");
    		String data[]=actionType.split("_");
    		try
    		{
    			Class<?> classNameObject;
    			Object actionClassObject;
    			classNameObject=Class.forName("com.onlinemart.view."+data[0]);
    			System.out.println(classNameObject);
    		    actionClassObject=classNameObject.newInstance();
    			System.out.println("View Object is Created");
    			Method businessMethod=classNameObject.getDeclaredMethod(data[1], HttpServletRequest.class, HttpServletResponse.class);
    			businessMethod.invoke(actionClassObject, request,response);
    		}
    		catch(Exception ex)
    		{
    			System.out.println("Exception happened in doProcess method of Servlet");
    			System.out.println("Or the Method invocation is not proper.");
    			ex.printStackTrace();
    		} 
    		
    	}
    	else if(session.getAttribute("userName")==null)
    	{
    		response.sendRedirect("user.jsp");
    	}
    	
    	
    }
    
    
}